package de.dopichaj.labrador.genetic;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import de.dopichaj.labrador.inex.Assessment;
import de.dopichaj.labrador.inex.assess.XCGAssessor;
import de.dopichaj.labrador.search.hit.DocHitMap;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.HitComparator;
import de.dopichaj.labrador.search.hit.HitHierarchyTree;
import de.dopichaj.labrador.search.merge.pattern.AbstractPattern;
import de.dopichaj.labrador.search.merge.pattern.PatternMerge;
import de.dopichaj.labrador.search.prune.ContextPruner;
import de.dopichaj.labrador.search.prune.ResultTreePruner;


public final class PatternFinder<T extends Individual<T>> {

    private static final Logger log = Logger.getLogger(PatternFinder.class);

    private final List<AssessedHit> allHits;
    private List<Individual<T>> population;
    private final Collection<HitHierarchyTree> trees;
    private final Pattern fileNamePattern;
    private final Random rand = new Random();
    private final XCGAssessor assessor;
    private Map<Individual<T>, Double> fitness;
    private final Map<String, Double> fitnessCache = new HashMap<String, Double>();
    private double maxFitness;
    private Individual<T> fittest;
    private double averageFitness;
    private double minFitness;
    
    private final double mutationRate = 0.1;

    
    public PatternFinder(final int populationSize,
        final IndividualFactory<T> factory,
        final Assessment assessments, final DocHitMap retrievalResults) {
        
        fileNamePattern = Pattern.compile(".*/(../\\d{4}/.*)\\.xml");
        
        // add assessments to hits
        this.trees = new ArrayList<HitHierarchyTree>(retrievalResults.getDocs().size());
        this.allHits = new ArrayList<AssessedHit>();
        for (final Collection<Hit> hits : retrievalResults.getHitSets()) {
            final Collection<Hit> assessedHits = new ArrayList<Hit>(hits.size());
            
            for (final Hit hit : hits) {
                final Matcher matcher = fileNamePattern.matcher(hit.getFile().toString());
                final String file = matcher.matches() ? matcher.group(1) : "";
                final String xPath = hit.getXPath();
                final AssessedHit aHit = new AssessedHit(hit,
                    assessments.getExhaustivity(file, xPath),
                    assessments.getSpecificity(file, xPath));
                allHits.add(aHit);
                assessedHits.add(aHit);
            }
            final HitHierarchyTree tree = new HitHierarchyTree(assessedHits);
            trees.add(tree);
        }
        
        // initialize the assessor
        assessor = new XCGAssessor(allHits);
        
        // initialize the population
        this.population = new ArrayList<Individual<T>>();
        for (int i = 0; i < populationSize; i++) {
            population.add(factory.makeRandomIndividual());
        }
    }

    public void evaluate() {
        
        fitness = new HashMap<Individual<T>, Double>();
        maxFitness = 0;
        minFitness = Double.MAX_VALUE;
        fittest = null;
        double fitnessSum = 0;
        for (final Individual<T> individual : population) {
            
            log.info("-> evaluating " + individual.getGenomeString());
            
            final String pattern = individual.getGenomeString();
            final double f = fitnessCache.containsKey(pattern) ?
                fitnessCache.get(pattern) :
                getFitness(individual);
            fitnessCache.put(individual.getGenomeString(), f);
            fitness.put(individual, f);
            
            if (f > maxFitness) {
                fittest = individual;
                maxFitness = f;
            }
            if (f < minFitness) {
                minFitness = f;
            }
            
            fitnessSum += f;
        }
        averageFitness = fitnessSum / population.size();
    }
    
    private static final class Limit<T extends Individual<T>> {
        final double limit;
        final Individual<T> individual;
        public Limit(double limit, Individual<T> individual) {
            this.limit = limit;
            this.individual = individual;
        }
    }
    
    private List<Limit<T>> getLimits(final Map<Individual<T>, Double> fitness) {
        
        double fitnessSum = 0;
        for (double f : fitness.values()) {
            fitnessSum += f;
        }
        
        double limitSum = 0;
        final List<Limit<T>> limits = new ArrayList<Limit<T>>(fitness.size());
        for (final Individual<T> ind : fitness.keySet()) {
            limitSum += fitness.get(ind);
            limits.add(new Limit<T>(limitSum / fitnessSum, ind));
        }
        return limits;
    }
    
    private void select() {
        
        final List<Limit<T>> limits = getLimits(fitness);
        
        final int size = population.size();
        final List<Individual<T>> newPopulation = new ArrayList<Individual<T>>(size);
        for (int i = 0; i < size; i++) {
            final double r = Math.random();
            
            for (final Limit<T> limit : limits) {
                if (r <= limit.limit) {
                    final Individual<T> newInd = limit.individual.copy();
                    newPopulation.add(newInd);
                    break;
                }
            }
        }
        population = newPopulation;
    }
    
    private void mutate() {
        
        for (final Individual<T> ind : population) {
            if (rand.nextDouble() < mutationRate) {
                log.info("Mutating " + ind.getGenomeString());
                ind.mutate();
                log.info("... new: " + ind.getGenomeString());
            }
        }
    }
    
    private void cross() {
        for (final Individual<T> ind : population) {
            if (rand.nextDouble() < 0.1) {
                log.info("Crossing " + ind.getGenomeString());
                final Individual<T> mate =
                    population.get(rand.nextInt(population.size()));
                ind.crossWith(mate.getImplementation());
                log.info("... new: " + ind.getGenomeString());
            }
        }
    }
    
    public void evolve() {
        select();
        cross();
        mutate();
    }
    
    public Collection<Individual<T>> getPopulation() {
        return Collections.unmodifiableCollection(population);
    }
    
    private double getFitness(final Individual<T> individual) {
        final AbstractPattern pattern = individual.getPattern();
        final PatternMerge patternMerge = new PatternMerge(pattern);
        final ResultTreePruner pruner = new ContextPruner(patternMerge);
        
        resetResultScores(allHits);

        // apply the individual's pattern
        for (final HitHierarchyTree tree : trees) {
            pruner.prune(tree);
        }
        
        boolean didChange = false;
        for (final AssessedHit hit : allHits) {
            if (hit.scoreHasChanged()) {
                didChange = true;
            }
        }
        
        if (didChange) {
            // determine the average fitness
            final HitComparator comparator = new HitComparator(HitComparator.SORT_BY_SCORE);
            Collections.sort(allHits, comparator);
            return assessor.assessMeanAverage(allHits);
        } else {
            return 0;
        }
    }

    private void resetResultScores(Collection<AssessedHit> hits) {
        for (final Hit hit : hits) {
            hit.setScore(1.0f);
        }
    }

    public double averageFitness() {
        return averageFitness;
    }
    
    public double maxFitness() {
        return maxFitness;
    }

    public Individual<T> getFittest() {
        return fittest;
    }
    
    public double minFitness() {
        return minFitness;
    }

    
    public static void main(String[] args)
        throws FileNotFoundException, SAXException, IOException,
            ParserConfigurationException {
        
        final Assessment assessment = new Assessment();
        final String assessmentFile = args[0];
        final String resultFile = args[1];
        
        log.info("Reading assessments ...");
        assessment.readTopic(
            new InputStreamReader(new FileInputStream(assessmentFile)), 127);
        
        log.info("Reading results ...");
        final DocHitMap results = new DocHitMap(new FileInputStream(resultFile));

        final int populationSize = args.length > 2 ? Integer.valueOf(args[2]) : 100;
        final int partCount = args.length > 3 ? Integer.valueOf(args[3]) : 6;
        final int patternCount = args.length > 4 ? Integer.valueOf(args[4]) : 2;
        
        
        log.info("Creating initial population ...");
        final PatternFinder<GenericPatternIndividual> finder =
            new PatternFinder<GenericPatternIndividual>(populationSize,
            new GenericPatternIndividualFactory(partCount, patternCount), assessment,
            results);

        final PatternFinderGUI gui = new PatternFinderGUI();
        Individual globalFittest = null;
        double globalMaxFitness = 0;
        for (int i = 0; i < 500; i++) {
            log.info("Evaluating generation " + i);
            finder.evaluate();
            
            final double maxFitness = finder.maxFitness();
            final double averageFitness = finder.averageFitness();
            gui.addValues(maxFitness, averageFitness, finder.minFitness());
            if (maxFitness > globalMaxFitness) {
                globalFittest = finder.getFittest();
                globalMaxFitness = maxFitness;
            }
            gui.setMessage(i + ", best individual: " + globalFittest.getGenomeString() +
                " (" + globalMaxFitness + ")");
            System.err.println(globalFittest.getGenomeString());
            System.out.println(averageFitness + "\t" + maxFitness);

            log.info("Evolving generation " + i);
            finder.evolve();
        }
        
        System.err.println("Best individual: " + globalFittest.getGenomeString());
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/